<template>
  <div class="setting-edit">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>课程封面</span>
          </div>
          <div class="avtar-wrap">
            <div class="avtar-item">
              <el-upload
                class="avatar-uploader"
                action=""
                accept=".png,.jpg,.jpeg"
                :show-file-list="false"
                ref='cvue-upload'
                :headers="accessToken"
                :on-preview="handlePictureCardPreview"
                :multiple="false"
                :http-request="uploadFile"
                :auto-upload="true"
                :file-list="fileList"
                :on-remove="handleRemove">
                <ul class="list-upload-image" v-if="frontImageFile">
                  <li><img :src="frontImageFile" class="image-item"></li>
                </ul>    
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">支持png/jpg，建议尺寸750*450px，大小不超过2M</div>
              </el-upload>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
          </div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="110px"
            class="demo-ruleForm">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="课程名称" prop="courseName">
                  <el-input v-model.trim="ruleForm.courseName" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="课程类型" prop="courseType">
                  <el-select v-model="ruleForm.courseType" placeholder="请选择" style="width:100%" clearable @change="changeType">
                    <el-option
                      v-for="item in courseTypeArr"
                      :key="item.dicCode"
                      :label="item.dicName"
                      :value="item.dicCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="ruleForm.courseType === 1">
              <el-col :span="8">
                <el-form-item label="课程模式" prop="courseMode">
                  <el-select v-model="ruleForm.courseMode" placeholder="请选择" style="width:100%" clearable>
                    <el-option
                      v-for="item in courseModeArr"
                      :key="item.dicCode"
                      :label="item.dicName"
                      :value="item.dicCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="ruleForm.courseType === 1">
              <el-col :span="8">
                <el-form-item label="课程时长" prop="courseTimes">
                  <el-select v-model="ruleForm.courseTimes" placeholder="请选择" style="width:100%" clearable>
                    <el-option
                      v-for="item in courseTimeArr"
                      :key="item.dicCode"
                      :label="item.dicName"
                      :value="item.dicCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item label="课程介绍" prop="introduce">
                  <el-input v-model.trim="ruleForm.introduce" :disabled="disabled" type="textarea" :rows="10"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="状态" prop="courseState">
                  <el-radio-group v-model="ruleForm.courseState">
                    <el-radio :label="item.dicCode" v-for="(item, index) in courseStateArr" :key="index">{{ item.dicName }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="课程图片" prop="coachMienFileIds">
                  <el-upload
                    class="avatar-uploader"
                    action=""
                    :show-file-list="false"
                    ref='cvue-upload1'
                    :headers="accessToken"
                    :on-preview="handlePictureCardPreview"
                    :multiple="false"
                    :limit="10"
                    accept=".png,.jpg,.jpeg"
                    :http-request="uploadFile1"
                    :auto-upload="true"
                    :file-list="fileList1"
                    :on-remove="handleRemove">
                    <ul v-if="ruleForm.courseImageFile.length >= 0" class="list-upload-image fix-upload">
                      <li><i class="el-icon-plus avatar-uploader-icon"></i></li>
                      <li v-for="(item,index) in ruleForm.courseImageFile" :key="index">
                        <img :src="item" class="image-item">
                        <i class="el-icon-close icon-close" @click.prevent.stop="deleteImage(index, ruleForm.courseImageFile, ruleForm.courseImageFileIds)"></i>
                      </li>
                    </ul>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <div class="edit-footer">
      <el-button @click="confirmDialog" type="primary">保存</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import cvueTable from '@/components/cvue-table'
import { validPhone, validIp, validInt } from '@/util/validator.js'
import coachCourseEdit from './coachCourseEdit'
import BMF from 'browser-md5-file'
const bmf = new BMF()
export default {
  name: 'course-setting-edit',
  components: {
    cvueTable,
    coachCourseEdit
  },
  data () {
    return {
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      ruleForm: {
        'courseImageFileIds': [],
        'courseImageFile': [],
        'courseMode': 1,
        'courseName': '',
        'courseState': 1,
        'courseTimes': '',
        'courseType': 1,
        'frontImageFileId': '',
        'introduce': ''
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        courseType: [
          { required: true, message: '请选择课程类型', trigger: 'blur' }
        ],
        courseMode: [
          { required: true, message: '请选择课程模式', trigger: 'blur' }
        ],
        courseTimes: [
          { required: true, message: '请输入课程时长', trigger: 'blur' }
        ],
        introduce: [
          { min: 0, max: 500, message: '长度在 0 到 500 个字符', trigger: 'blur' }
        ]
      },
      disabled: false,
      fileList: [],
      fileList1: [],
      fileList2: [],
      fileList3: [],
      fileList4: [],
      storeArr: [],
      dialogCoachCourseEdit: false,
      frontImageFile: '',
      frontImageFileId: '',
      courseId: '',
      courseModeArr: [],
      courseStateArr: [],
      courseTypeArr: [],
      courseTimeArr: [
        {dicName: '30分钟', dicCode: 30},
        {dicName: '60分钟', dicCode: 60},
        {dicName: '90分钟', dicCode: 90},
        {dicName: '120分钟', dicCode: 120},
        {dicName: '150分钟', dicCode: 150},
        {dicName: '180分钟', dicCode: 180},
        {dicName: '210分钟', dicCode: 210},
        {dicName: '240分钟', dicCode: 240},
        {dicName: '270分钟', dicCode: 270},
        {dicName: '300分钟', dicCode: 300}
      ]
    }
  },
  beforeRouteLeave (to, from, next) {
    // if (this.$route.query.action == 'edit') {
    //   this.$confirm('确定要离开编辑页面吗?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     next()
    //   }).catch(() => {  
    //     location.reload()       
    //   })
    // } else {
    //   next()
    // }
    next()
  },
  computed: {
    ...mapGetters(['token', 'userInfo', 'tagCurrent']),
    accessToken () {
      var accessToken = {
        'Authorization': this.token
      }
      return accessToken
    }
  },
  created () {
    this.getDic().then(res => {
      // console.log(res)
      this.dict = res.data
      this.dict.forEach((item, index) => {
        if (item.dicName == 'CourseMode') {
          this.courseModeArr = item.dicValueList
        }
        if (item.dicName == 'CourseState') {
          this.courseStateArr = item.dicValueList
        }
        if (item.dicName == 'CourseType') {
          this.courseTypeArr = item.dicValueList
        }
      })
    })
    if (this.$route.query.action == 'edit') {
      this.getCourseDetail()
    }
  },
  mounted () {
  },
  methods: {
    changeType (val) {
      // console.log(val)
      this.$set(this.ruleForm, 'courseMode', '')
      this.$set(this.ruleForm, 'courseTimes', '')
    },
    // 自定义文件上传
    uploadFile (param) { 
      var fileObj = param.file
      bmf.md5(fileObj, (err, md5) => {
        console.log(err, 1)
        var formData = new FormData()
        formData.append('file', fileObj)    
        formData.append('explorerId', -1)
        formData.append('md5', md5)
        formData.append('name', fileObj.name)
        formData.append('parentId', -1)
        this.$store.dispatch('fileFun/UploadFile', formData).then(res => {
          if (res.code == '200') {
            this.frontImageFileId = res.data.fileId
            this.getPic(this.frontImageFileId).then(response => {
              this.frontImageFile = response.data
            })
          }
        })
      })
    },
    // 自定义文件上传
    uploadFile1 (param) { 
      var fileObj = param.file
      bmf.md5(fileObj, (err, md5) => {
        console.log(err, 1)
        var formData = new FormData()
        formData.append('file', fileObj)    
        formData.append('explorerId', -1)
        formData.append('md5', md5)
        formData.append('name', fileObj.name)
        formData.append('parentId', -1)
        this.$store.dispatch('fileFun/UploadFile', formData).then(res => {
          if (res.code == '200') {
            this.ruleForm.courseImageFileIds.push(res.data.fileId)
            this.getPic(res.data.fileId).then(response => {
              this.ruleForm.courseImageFile.push(response.data)
            })
          }
        })
      })
    },
    submitUpload () {
      this.$refs['cvue-upload'].submit()
    },
    handlePictureCardPreview () {},
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handleResetForm () {
      this.$refs['ruleForm'].resetFields()
    },
    getCourseDetail () {
      var params = {
        id: this.$route.query.id
      }
      this.$store.dispatch('manage/CourseGetById', params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          var data = res.data
          this.$set(this.ruleForm, 'courseName', data.courseName)
          this.$set(this.ruleForm, 'courseType', data.courseType)
          this.$set(this.ruleForm, 'courseMode', data.courseMode)
          this.$set(this.ruleForm, 'courseTimes', data.courseTimes)
          this.$set(this.ruleForm, 'introduce', data.introduce)
          this.$set(this.ruleForm, 'courseState', data.courseState)
          this.frontImageFileId = data.frontImageFileId
          var courseImageFileIds = data.imageFileIds
          this.courseId = data.id
          // console.log(this.frontImageFileId)
          this.getPic(this.frontImageFileId).then(response => {
            // console.log(response)
            this.frontImageFile = response.data
          })
          this.getPicList(courseImageFileIds).then(res => {
            // console.log(res)
            for (var key in res.data) {
              this.ruleForm.courseImageFile.push(res.data[key])
              this.ruleForm.courseImageFileIds.push(key)
            }
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getPic (fileId) {
      var paramsData = {
        fileId: fileId
      }
      return this.$store.dispatch('fileFun/GetPublicUrl', paramsData)
    },
    getPicList (fileIds) {
      return this.$store.dispatch('fileFun/ListPublicUrl', fileIds)
    },
    deleteImage (index, imageFiles, imageFileIds) {
      imageFiles.splice(index, 1)
      imageFileIds.splice(index, 1)
    },
    handleEdit () {
      this.dialogCoachCourseEdit = true
    },
    // 关闭弹窗
    closeSecDialog (params) {
      if (params == 'edit') {
        this.dialogCoachCourseEdit = false
      }
    },
    // 确认
    confirmSecDialog (params) {
      if (params == 'edit') {
        this.dialogCoachCourseEdit = false
      }
    },
    // 关闭弹窗
    closeDialog () {
      this.closeTagTo('/home/course-setting')
    },
    // 确认
    confirmDialog () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var params = {
            'courseImageFileIds': this.ruleForm.courseImageFileIds,
            'courseMode': this.ruleForm.courseMode,
            'courseName': this.ruleForm.courseName,
            'courseState': this.ruleForm.courseState,
            'courseTimes': this.ruleForm.courseTimes,
            'courseType': this.ruleForm.courseType,
            'frontImageFileId': this.frontImageFileId,
            'introduce': this.ruleForm.introduce,
            'id': this.$route.query.action == 'add' ? '' : this.courseId
          }
          // console.log(params)
          this.dialogLoading = true
          var url = this.$route.query.action == 'add' ? 'manage/CourseAdd' : 'manage/CourseEdit'
          this.$store.dispatch(url, params).then(res => {
            // console.log(res)
            if (res.code == '200') {
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'success'
              })
              this.closeTagTo('/home/course-setting')
            } else {
              this.$message({ message: res.msg, duration: 2000, type: 'error' })
            }
            this.dialogLoading = false
          }).catch(err => {
            console.log(err)
            this.dialogLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.setting-edit {
  padding: 0px 0 60px !important;
  height: auto !important;
  position: relative;
  .btn-list {
    float: right;
    margin-right: 10px;
    font-size: 12px;
    color: #409EFF;
    cursor: pointer;
  }
  .el-card__header,
  .el-card__body {
    padding: 15px;
  }
  .fix-lh {
    line-height: 32px;
  }
  .el-input.is-disabled .el-input__inner {
    color: #606266;
  }
  .left{
    min-height:500px;
    background:#fff;
  }
  .left-tree{
    width: 100%;
    min-height:600px;
    overflow: auto;
  }
  .left-top{
    width: 100%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 16px;
    color: #333;
    background: #e2e2e2;
    font-size: 15px;
  }
  .box-card{
    margin-bottom: 10px;
  }
  .avtar-wrap{
    padding: 10px 30px 30px;
    .avtar-item{
      width: 158px;
      margin: 0 auto 50px;
      p{
        line-height: 26px;
        color: #bbb;
      }
      .avtar-img{
        width: 158px;
        height: 158px;
      }
      .avtar-tip{
        color: #555;
      }
    }
  }

  .avatar-uploader {
    .el-upload{
      // display: flex;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader-icon:hover{
      border-color: #409EFF;
    }
    .fix-upload .avatar-uploader-icon{
      border: none;
    }
    .list-upload-image{
      // max-width: 800px;
      overflow: hidden;
      li{
        width: 148px;
        height: 148px;
        line-height: 148px;
        display: inline-block;
        margin: 0 5px 5px;
        border: 1px dashed #d9d9d9;
        float: left;
        position: relative;
        .image-item{
          // width: 100%;
          // height: 100%;
          max-width: 100%;
          max-height: 100%;
          vertical-align: middle;
        }
        .icon-close{
          position: absolute;
          right: 0px;
          top: 0px;
          color: red;
          font-size: 18px;
        }
      }
    }
  }
  .edit-footer{
    width: calc(100% - 248px);
    height: 60px;
    line-height: 60px;
    position: fixed;
    background: #fff;
    left: 230px;
    bottom: 0;
    padding-left: 20px;
    box-sizing: border-box;
  }
  #addressMap{
    width: 100%;
    height: 300px;
  }
  .fix-address{
    margin-bottom: 0px !important;
  }
}
</style>
